//
//  CYAddressBookCell.m
//  CreditAddressBook
//
//  Created by Lee on 15/7/9.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYAddressBookCell.h"
#import "CYPerson.h"
#import "UIImageView+WebCache.h"
#import "CYABTool.h"
#import "CYEscape.h"
#import "objc/runtime.h"

static char loadOperationKey;
//static char selfKey;

@interface CYAddressBookCell ()

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;

//@property (strong, nonatomic) NSString *nameTag;//防止图片错乱tag
@end

@implementation CYAddressBookCell

- (void)setPerson:(CYPerson *)person {
    _person = person;
    
    __block RHPerson *rhperson = person.person;
    self.nameLabel.text = person.name;
    self.phoneLabel.text = [CYABTool formatPhoneNumbers:rhperson.phoneNumbers.values].firstObject;
    
    if (rhperson.thumbnail) {
        [self.headImageView setImage:rhperson.thumbnail];
    } else if (person.simpleRecord.headPic && ![person.simpleRecord.headPic isEqualToString:@""]) {
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:person.simpleRecord.headPic] placeholderImage:[UIImage imageNamed:@"ic_contact_info_header"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [rhperson setImage:image];
            [rhperson save];
        }];
    } else {
        [self.headImageView setImage:[UIImage imageNamed:@"ic_contact_info_header"]];
    }
    //取消队列中的下任务
    [self cancelCurrentImageLoad];
    //疑似失信人匹配
    self.iconBtn.hidden = !person.show;
    if (person.show) {
        if (person.iconType == CYIconTypeYS) {
            [self.iconBtn setBackgroundImage:[UIImage imageWithName:@"icon_ys50"] forState:UIControlStateNormal];
        } else {
            [self.iconBtn setBackgroundImage:[UIImage imageWithName:@"icon_sx50"] forState:UIControlStateNormal];
        }
    } else {
        if (person.iconType != CYIconTypeDefault) {
            [self loadYSX:person];
        }
    }
}

+ (instancetype)cellWithTableView:(UITableView *)tableView {
    static NSString *ID = @"newCell";
    CYAddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CYAddressBookCell" owner:nil options:nil] lastObject];
    }
    return cell;
}

- (void)iconBtnAddTarget:(id)target action:(SEL)action {
    [self.iconBtn addTarget:target action:action forControlEvents:UIControlEventTouchDown];
}

- (IBAction)iconBtnClick:(UIButton *)sender {
    if ([self.cellDelegate respondsToSelector:@selector(cell:iconButton:)]) {
        [self.cellDelegate cell:self iconButton:sender];
    }
}

/**
 *  服务器加载失信人
 *
 *  @param person
 */
- (void)loadYSX:(CYPerson *)person {
    self.iconBtn.hidden = YES;
//    self.nameTag = self.person.name;
    
    if (person && person.name) {
        NSDictionary *nameDic = @{@"name": person.name};
        NSString *json = [NSString jsonStringWithArray:@[nameDic]];
        AFHTTPRequestOperation *operation = [CYABTool ysDefaultPersonsWithParams:@{@"data": json} success:^(NSArray *defrs) {
            person.iconType = CYIconTypeYS;
            person.show = YES;
            
//            CYPerson *cyperson = defrs.firstObject;
//            if ([self.nameTag isEqualToString:cyperson.name]) {
                [self.iconBtn setBackgroundImage:[UIImage imageWithName:@"icon_ys50"] forState:UIControlStateNormal];
                self.iconBtn.hidden = NO;
                [self.iconBtn setNeedsLayout];
//            } else {
//                
//                CYLog(@"namegTag = %@, personName = %@", self.nameTag, cyperson.name);
//            }
            
        } failure:^(NSError *error) {
            if (error.code == CYErrorCodeNOData) {
                //服务器返回空数据的设置icon显示为默认不显示
                person.iconType = CYIconTypeDefault;
                self.iconBtn.hidden = YES;
                [self.iconBtn setNeedsLayout];
            } else if (error.code == -999) {
//                CYLog(@"3person:%@", person.name);
            }
        }];

        [self setImageLoadOperation:operation forKey:@"UIImageViewImageStatusLoad"];
//        objc_setAssociatedObject(self, &operationKey, operation, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        //将self与person关联
//        objc_setAssociatedObject(person, &selfKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}

#pragma mark -取消队列中的下载任务
/**
 *  取消队列中的下载任务
 */
- (void)cancelCurrentImageLoad {
    [self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageStatusLoad"];
//    AFHTTPRequestOperation *operation = objc_getAssociatedObject(self, &operationKey);
//    if (operation) {
//        [operation cancel];
//        objc_setAssociatedObject(self, &operationKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//    }
}

- (void)setImageLoadOperation:(AFHTTPRequestOperation *)operation forKey:(NSString *)key {
    [self sd_cancelImageLoadOperationWithKey:key];
    NSMutableDictionary *operationDictionary = [self operationDictionary];
    [operationDictionary setObject:operation forKey:key];
}

- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
    NSMutableDictionary *operationDictionary = [self operationDictionary];
    id operations = [operationDictionary objectForKey:key];
    if (operations) {
        if ([operations isKindOfClass:[NSArray class]]) {
            for (AFHTTPRequestOperation *operation in operations) {
                if (operation) {
                    [operation cancel];
                }
            }
        } else if ([operations isKindOfClass:[AFHTTPRequestOperation class]]){
            [(AFHTTPRequestOperation *) operations cancel];
        }
        [operationDictionary removeObjectForKey:key];
    }
}

- (NSMutableDictionary *)operationDictionary {
    NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
    if (operations) {
        return operations;
    }
    operations = [NSMutableDictionary dictionary];
    objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    return operations;
}

#pragma mark - 创建对象时调用，重用时不会调用
- (void)awakeFromNib {
    self.headImageView.layer.cornerRadius = 20;
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.borderColor = [CYNaviThemeColor CGColor];
    self.headImageView.layer.borderWidth = 1;
}

- (UIEdgeInsets)layoutMargins {
    return UIEdgeInsetsZero;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];
    [self cellAnimationForObject:self.nameLabel];
    [self cellAnimationForObject:self.phoneLabel];
    [self cellAnimationForObject:self.headImageView];
}

@end
